﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Freejobber.Core.Generic.Profile;
using Freejobber.Core.Generic;

namespace Freejobber.UserControls
{
    public partial class ImageUploader : System.Web.UI.UserControl
    {
        public byte[] ImageData;
        public string UserLogin;

        protected void Page_Load(object sender, EventArgs e)
        {

        }

        protected void UploadButton_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(UserLogin))
            {
                StatusLabel.Text = "User login is empty";
                return;
            }

            //if (SaveImage())
            //    AddUserAvatar();
            SaveImage();
        }

        private void AddUserAvatar()
        {
            UserClass _user = new UserClass(UserLogin);
            _user.Save();
        }

        private bool SaveImage()
        {
            bool result = false;
            IAvatarManager _am = new FileSystemAvatarManager();
            if (FileUploadControl.HasFile)
            {
                try
                {
                    if (FileUploadControl.PostedFile.ContentType == "image/jpeg")
                    {
                        if (FileUploadControl.PostedFile.ContentLength < 102400)
                        {
                            ImageData = FileUploadControl.FileBytes;
                            _am.SaveAvatar(UserLogin, ImageData);
                            StatusLabel.Text = "Upload status: File uploaded!";
                            result = true;
                        }
                        else
                            StatusLabel.Text = "Upload status: The file has to be less than 100 kb!";
                    }
                    else
                        StatusLabel.Text = "Upload status: Only JPEG files are accepted!";
                }
                catch (Exception ex)
                {
                    StatusLabel.Text = "Upload status: The file could not be uploaded. The following error occured: " + ex.Message;
                }
            }
            return result;
        }
        
    }
}